<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加按钮 -->
      <el-button type="primary" @click="showAddRolesForm">添加角色</el-button>
      <!-- 用户角色列表 -->
      <el-table :data="rolesList" style="width: 100%" stripe border>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 一级权限 -->
            <el-row
              v-for="(item, index) in scope.row.children"
              :key="index"
              :class="index === 0 ? 'el-row-first' : ''"
              hit
              class="el-tag-center"
            >
              <el-col :span="5">
                <el-tag closable @close="deleteRoles(item, scope.row)">{{
                  item.authName
                }}</el-tag>
                <el-icon class="el-icon-caret-right"></el-icon>
              </el-col>
              <el-col :span="19">
                <el-row
                  v-for="(item1, index) in item.children"
                  :key="index"
                  hit
                  :class="
                    index === item.children.length - 1 ? 'el-row-none' : ''
                  "
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      closable
                      type="success"
                      @close="deleteRoles(item1, scope.row)"
                      >{{ item1.authName }}</el-tag
                    >
                    <el-icon class="el-icon-caret-right"></el-icon>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      v-for="(item2, index) in item1.children"
                      :key="index"
                      hit
                      type="warning"
                      closable
                      @close="deleteRoles(item2, scope.row)"
                      >{{ item2.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称" align="center">
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述" align="center">
        </el-table-column>
        <el-table-column label="操作" align="center" width="300">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showModRolesForm(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="delRole(scope.row)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="distPowers(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分配权限对话框 -->
      <el-dialog
        title="分配权限"
        :visible.sync="dialogPowers"
        width="50%"
        @close="closeDialogPowers"
      >
        <el-tree
          ref="PowersRefs"
          :data="powerList"
          node-key="id"
          :props="powersProps"
          default-expand-all
          show-checkbox
          :default-checked-keys="defChecked"
        >
        </el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogPowers = false">取 消</el-button>
          <el-button type="primary" @click="sumbitPowersList()"
            >确 定</el-button
          >
        </span>
      </el-dialog>
      <!-- 添加用户角色对话框 -->
      <el-dialog
        title="添加角色"
        :visible.sync="addRoleVisible"
        width="50%"
        @close="cloAddRoleDialog"
      >
        <el-form
          ref="addRolesFormRef"
          :rules="addRolesRules"
          :model="addRolesParams"
          label-width="80px"
          status-icon
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRolesParams.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRolesParams.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addRoleVisible = false">取 消</el-button>
          <el-button type="primary" @click="subAddRolesForm">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户角色对话框 -->
      <el-dialog title="修改角色" :visible.sync="modRoleVisible" width="50%">
        <el-form
          ref="modRolesFormRef"
          :rules="modRolesRules"
          :model="modRolesParams"
          label-width="80px"
          status-icon
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="modRolesParams.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="modRolesParams.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="modRoleVisible = false">取 消</el-button>
          <el-button type="primary" @click="subModRolesForm">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 用户角色列表
      rolesList: [],
      // 分配权限对话框
      dialogPowers: false,
      // 权限列表
      powerList: [],
      // 权限列表树状图配置
      powersProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认权限列表显示数组
      defChecked: [],
      // 当前用户id
      uid: '',
      // 添加角色对话框
      addRoleVisible: false,
      // 添加角色表单参数
      addRolesParams: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色表单规则
      addRolesRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 修改角色对话框
      modRoleVisible: false,
      // 修改角色表单参数
      modRolesParams: {
        roleName: '',
        roleDesc: ''
      },
      // 修改角色表单规则
      modRolesRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取用户角色列表
    async getRolesList() {
      const { data } = await this.$http.get('roles')
      if (data.meta.status !== 200) {
        return this.$message.error('用户角色列表获取失败！')
      }
      // this.$message.success('用户角色列表获取成功！')
      console.log('用户角色列表获取成功！')
      this.rolesList = data.data
      console.log(this.rolesList)
    },
    // 删除用户角色权限
    deleteRoles(item, row) {
      this.$confirm(`是否删除< ${item.authName} >角色权限?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data } = await this.$http.delete(
            `roles/${row.id}/rights/${item.id}`
          )
          if (data.meta.status !== 200) {
            return this.$message.error(`删除< ${item.authName} >角色权限失败!`)
          }
          /***
           * 注意:这里不能直接调用this.getRolesList()刷新列表
           * 问题:若使用会导致深渲染(相当于一次刷新),下拉项会自动关闭
           * 解决:获取当前列的children信息,里面包含所有权限列表,把删除返回的数据
           *      给children属性,这样动态改变数据,实现页面渲染
           * ***/
          row.children = data.data
          this.$message({
            type: 'success',
            message: `删除< ${item.authName} >角色权限成功!`
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 分配权限对话框
    async distPowers(role) {
      const { data } = await this.$http.get('rights/tree')
      if (data.meta.status !== 200) {
        return this.$message.error('权限列表获取失败！')
      }
      // this.$message.success('权限列表获取成功！')
      console.log('权限列表获取成功！')
      this.powerList = data.data
      console.log(data.data)
      // 获取三级节点id
      this.handleDefChecked(role, this.defChecked)
      this.uid = role.id
      this.dialogPowers = true
    },
    // 默认权限列表显示数据处理
    handleDefChecked(node, array) {
      // 若没有子节点就是第三权限
      if (!node.children) {
        return array.push(node.id)
      }
      // 若有子节点，就遍历子节点，实现回溯函数
      node.children.forEach(el => {
        this.handleDefChecked(el, array)
      })
    },
    // 关闭分配权限列表事件
    closeDialogPowers() {
      this.defChecked = []
    },
    // 提交分配权限列表
    async sumbitPowersList() {
      // 获取选中和半选中
      const key = [
        ...this.$refs.PowersRefs.getHalfCheckedKeys(),
        ...this.$refs.PowersRefs.getCheckedKeys()
      ]
      const subPowerParams = key.join(',')
      console.log(subPowerParams)
      const { data } = await this.$http.post(`roles/${this.uid}/rights`, {
        rids: subPowerParams
      })
      if (data.meta.status !== 200) {
        return this.$message.error('添加权限失败！')
      }
      this.$message.success('添加权限成功！')
      console.log('添加权限成功！')
      this.getRolesList()
      this.dialogPowers = false
    },
    // 是否显示添加角色表单
    showAddRolesForm() {
      this.addRoleVisible = true
    },
    // 提交添加角色表单
    subAddRolesForm() {
      this.$refs.addRolesFormRef.validate(async valid => {
        if (!valid) return false
        const { data } = await this.$http.post('roles', this.addRolesParams)
        console.log(data)
        if (data.meta.status !== 201) {
          this.addUserVisible = false
          return this.$message({ message: '添加角色失败', type: 'error' })
        }
        this.$message({ message: '添加角色成功', type: 'success' })
        this.addRoleVisible = false
        this.getRolesList()
      })
    },
    // 添加角色对话框关闭
    cloAddRoleDialog() {
      this.$refs.addRolesFormRef.resetFields()
    },
    // 是否显示修改角色表单
    async showModRolesForm(row) {
      const { data } = await this.$http.get(`roles/${row.id}`)
      if (data.meta.status !== 200) {
        this.addRoleVisible = false
        return this.$message({ message: 'id获取角色信息失败', type: 'error' })
      }
      // this.$message({ message: 'id获取角色信息成功', type: 'success' })
      console.log('id获取角色信息成功')
      this.modRolesParams.roleName = data.data.roleName
      this.modRolesParams.roleDesc = data.data.roleDesc
      this.uid = row.id
      this.modRoleVisible = true
    },
    // 提交修改角色表单
    subModRolesForm() {
      this.$refs.modRolesFormRef.validate(async valid => {
        if (!valid) return false
        const { data } = await this.$http.put(
          `roles/${this.uid}`,
          this.modRolesParams
        )
        console.log(data)
        if (data.meta.status !== 200) {
          this.modRoleVisible = false
          return this.$message({ message: '角色更新失败', type: 'error' })
        }
        this.$message({ message: '角色更新成功', type: 'success' })
        this.modRoleVisible = false
        this.getRolesList()
      })
    },
    // 删除角色
    delRole(row) {
      console.log(row)
      this.$confirm(`是否删除 ${row.roleName} 角色?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data } = await this.$http.delete(`roles/${row.id}`)
          console.log(data)
          if (data.meta.status !== 200) {
            return this.$message({
              type: 'error',
              message: ` ${row.roleName} 角色删除失败!`
            })
          }
          this.$message({
            type: 'success',
            message: ` ${row.roleName} 角色删除成功!`
          })
          this.getRolesList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>

<style lang="less" scoped>
.el-row-first {
  border-top: 1px solid #eee;
}
.el-row-none {
  border-bottom: none !important;
}
.el-row {
  padding: 20px 0;
  border-bottom: 1px solid #eee;
}
.el-table {
  margin-top: 10px;
}
.el-tag {
  margin: 10px;
}
.el-tag-center {
  display: flex;
  align-items: center;
}
</style>
